package my.study.demo.proxy.jhlproxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class JHLClassLoader extends ClassLoader {
    private File classPathFile;
    public JHLClassLoader() {
        String classPath = JHLClassLoader.class.getResource("").getPath();
        //D:\java\selfstudypro\com.my.study\target\classes\my\study\demo\proxy\jhlproxy
        this.classPathFile = new File(classPath);
    }




    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //my.study.demo.proxy.jhlproxy.$Proxy0
        String className = JHLClassLoader.class.getPackage().getName()+"."+name;

        if(classPathFile != null) {
            File classFile = new File(classPathFile, name.replaceAll("\\.","/")+".class");
            if(classFile.exists()) {

                FileInputStream in = null;
                ByteArrayOutputStream out = null;
                try {
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] buff = new byte[1014];//缓冲区
                    int len;
                    //等于-1表明写完了,
                    //从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
                    //把in中的数据读到定义的缓冲区buff中，一旦read的返回值是-1就表明in中的数据都读完了，
                    //而每读完一次数据后就会把这次读到缓冲区的数据再写到out中，最终都读完了 再out.toByteArray()输出
                    while((len = in.read(buff)) != -1) {
                        out.write(buff, 0,len);
                    }
                    return defineClass(className, out.toByteArray(),0,out.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
